<template>
  <div>
    <div class="too">购物清单</div>
    <div v-for="item in list" :key="item.id" class="we">
      <div class="uu">
        <input type="checkbox" v-model="item.checked" />
        <span>
          <img :src="item.img" alt />
        </span>
        <span>{{ item.name }}</span>
      </div>

      <div class="rt">
        <span>￥{{ item.price }}</span>
        <button @click="item.num > 1 ? item.num-- : ''">-</button>
        {{ item.num }}
        <button @click="item.num++">+</button>
      </div>
    </div>
    <div class="eer">
      <span> <input type="checkbox" @click="all" />全选 </span>
      <span>合计:￥{{ num }}</span>
      <span>数量{{ num1 }}</span>
    </div>
  </div>
</template>

<script>
import { ref, watch } from "vue";
import axios from "axios";
export default {
  setup() {
    const list = ref([]);
    const num = ref(0);
    const num1 = ref(0);

    axios.get("/data.json").then((res) => {
      list.value = res.data.cartData;
    });
    watch(
      () => list,
      (val) => {
        num.value = 0;
        num1.value = 0;

        val.value.forEach((item) => {
          if (item.checked) {
            num.value += item.num * item.price;
            num1.value += item.num;
          }
        });
      },
      {
        deep: true,
      }
    );

    function all(e) {
      list.value.forEach((item) => {
        item.checked = e.target.checked;
      });
    }

    return {
      list,
      all,
      num,
      num1,
    };
  },
};
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  bottom: 0;
}
.rt {
  margin-top: -30px;
}
.eer {
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  width: 100%;
  height: 50px;
  justify-content: space-between;
  background-color: rgb(170, 209, 107);
  line-height: 50px;
}
.we {
  width: 100%;
  height: 100px;
  background-color: rgb(33, 175, 231);
  margin: 10px 20px;
}
img {
  width: 90px;
  height: 90px;
}
.too {
  width: 100%;
  height: 40px;
  line-height: 40px;
  color: rgb(114, 233, 183);
  text-align: center;
}
.uu {
  display: flex;
}
</style>